package utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class FileTools {
    public static String readTextFile(String fileFullPath, Charset ENCODING) throws IOException {
        String fileContent = "";
        
//        Path path = Paths.get(fileFullPath);
//        try (Scanner scanner = new Scanner(path, ENCODING.name())) {
//            while (scanner.hasNextLine()) {
//                fileContent += scanner.nextLine() + "\n";
//            }
//        }
        
        BufferedReader reader = new BufferedReader (new InputStreamReader (new FileInputStream (fileFullPath), ENCODING));
        String line = null;
        while ((line = reader.readLine()) != null) {
            fileContent += line + "\n";
        }
        reader.close();

        return fileContent;
    }

    public static List<String> readLinesTextFile(String fileFullPath, Charset ENCODING){
        Path path = Paths.get(fileFullPath);
        try {
            return Files.readAllLines(path, ENCODING);
        } catch (IOException ex) {
            return null;
        }
    }

    /*
     * Remplit foundFiles; liste des fichiers trouvés
     */
    public static void findFiles(String folderPath, ArrayList<File> foundFiles) {
        if(foundFiles == null) foundFiles = new ArrayList<File>();
        
        File currentForlderAsFile = new File(folderPath);
        
        //Le chemin en paramètre est un fichier
        if(!currentForlderAsFile.isDirectory()){
            foundFiles.add(currentForlderAsFile);
            return;
        }
        
        File root = new File(folderPath);
        File[] list = root.listFiles();
        
        for (File f : list) {
            if (f.isDirectory()) {
                findFiles(f.getAbsolutePath(), foundFiles);
                //System.out.println("Dossier:" + f.getAbsoluteFile());
            } else {
                foundFiles.add(f);
                //System.out.println("Fichier:" + f.getAbsoluteFile());
            }
        }
    }
}
